package com.example.bankmanage.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.bankmanage.dto.rep.*;
import com.example.bankmanage.entity.PageBean;
import com.example.bankmanage.entity.cards;
import com.example.bankmanage.result.Result;
import com.example.bankmanage.service.CardService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Date;
import java.time.LocalDate;

@RestController
@RequestMapping("/api")
@Slf4j
public class CardController {
    @Autowired
    private CardService cardService;
    @PostMapping("/cards")
    public Result<PageBean> fetchCardList(@RequestBody CardReqDTO requestParam){
//        System.out.println(requestParam);
        PageBean<cards> pageBean = cardService.fetchCardList(requestParam);
        return Result.success(pageBean);
    }
    @GetMapping("/cards")
    public Result<cards> getCardDetail(@RequestParam Integer cardId){
        cards cards1 = cardService.getCardDetail(cardId);
        return Result.success(cards1);
    }
    @PostMapping("/addCard")
    public Result createCard(@RequestBody CreateCardReqDTO requestParam){
        log.info("添加卡号操作已经执行");
        cardService.createCard(requestParam);
        return Result.success();
    }
    @PutMapping("/updateCard")
    public Result updateCard(@RequestParam Integer cardId, @RequestBody UpdateCardReqDTO requestParam){
        log.info("修改指令已经执行");
        System.out.println(requestParam);
        cardService.updateCard(cardId,requestParam);
        return Result.success();
    }
    @GetMapping("/card/exportCard")
    public void exportCard(@RequestParam(required = false) String cardNumber,@RequestParam(required = false) String cardType,
                              @RequestParam(required = false) String status, @RequestParam(required = false) Integer accountId,
                           @RequestParam(required = false) String startDate,
                              @RequestParam(required = false) String endDate, HttpServletResponse response)throws IOException {
        System.out.println("sha");
        log.info("导出参数: cardNumber={}, cardType={}, status={},accountId={},startDate={},endDate={}",
                cardNumber, cardType, status,accountId,startDate,endDate);

        // 关键修改1: 确保在异常时重置response
        response.reset();

        try {
            // 1. 构建查询参数
            CardExportReqDTO exportDTO = new CardExportReqDTO();
            exportDTO.setCardNumber(cardNumber);
            exportDTO.setCardType(cardType);
            exportDTO.setStatus(status);
            exportDTO.setAccountId(accountId);

            // 日期转换处理
            if (StringUtils.isNotBlank(startDate)) {
                try {
                    exportDTO.setStartDate(Date.valueOf(startDate));
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("开始日期格式不正确，应为YYYY-MM-DD");
                }
            }
            if (StringUtils.isNotBlank(endDate)) {
                try {
                    exportDTO.setEndDate(Date.valueOf(endDate));
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("结束日期格式不正确，应为YYYY-MM-DD");
                }
            }

            // 2. 设置响应头
            String fileName = "卡片_" + LocalDate.now() + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 3. 导出Excel
            cardService.exportCard(exportDTO, response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            log.error("导出Excel失败", e);
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.getWriter().write(JSON.toJSONString(Result.error("导出失败: " + e.getMessage())));
        }
    }
}
